import axios, { type AxiosInstance, type AxiosRequestConfig } from "axios"
import qs from "qs"

import { ElMessage } from "element-plus"
import { merge } from "lodash-es"
import { getToken, removeToken, removeAccessToken, getAccessToken } from "@/utils/token"
import { useUserStore } from "@/store/modules/user"

enum NULLTOKNE {
  LOGIN = "/api/v2/login/login"
}
/** 创建请求实例 */
function createService() {
  // 创建一个 axios 实例命名为 service
  const service = axios.create()

  if (process.env.NODE_ENV == "development") service.defaults.baseURL = import.meta.env.VITE_IP

  console.info(service.defaults.baseURL)

  // 请求拦截
  service.interceptors.request.use(
    (config) => {
      const sign: string = getAccessToken()
      // 登录接口不需要token
      if (NULLTOKNE.LOGIN !== config.url || config.method !== "post") {
        config.headers.token = getToken() || sign
      }

      config.data = {
        company: "BL",
        device_name: "TE-0600R",
        data: config.data,
        sign,
        actioncode: `${config.method?.toLowerCase()}_${config.url?.replace(/.*\//, "")}`
      }
      if (config.method == "post" || config.method == "put") config.data = qs.stringify(config.data)

      if (config.method == "get") {
        config.params = {
          company: "BL",
          device_name: "TE-0600R",
          sign,
          actioncode: `${config.method?.toLowerCase()}_${config.url?.replace(/.*\//, "")}`,
          ...config.params
        }
      }
      return config
    },
    // 发送失败
    (error) => Promise.reject(error)
  )
  // 响应拦截（可根据具体业务作出相应的调整）
  service.interceptors.response.use(
    async (response: any) => {
      const res = response
      if (res.status !== 200) {
        if (res.data.result == 505) {
          removeToken()
          removeAccessToken()
          location.reload()
        }
        const msg = res.return_message || "error"
        ElMessage({
          message: msg,
          grouping: true,
          type: "error"
        })
        return Promise.reject(new Error(res.return_message || "Error"))
      }
      return res.data
    },
    (error) => {
      let errMessage = "网络请求失败"
      const userStore = useUserStore()

      if (error.message.includes("timeout")) {
        errMessage = "请求超时，请刷新页面重试！"
      } else if (error.message?.includes("Network Error")) {
        errMessage = "网络异常，请检查您的网络连接是否正常！"
      } else if (error.message.includes("401")) {
        errMessage = "登录已过期！"
        userStore.toLogin()
      } else if (error.message.includes("403")) {
        errMessage = "您的账户已被删除，请联系管理员"
        userStore.toLogin()
      } else if (error.message.includes("404")) {
        errMessage = "网络请求错误，未找到该资源！"
      } else if (error.message.includes("505")) {
        errMessage = "登录已过期！"
        userStore.logout()
      } else if (error.message.includes("606")) {
        errMessage = "平台使用权限已过期！"
        // 跳到激活页面
        const userStore = useUserStore()
        userStore.platformAuthExpired()
      }
      ElMessage({
        message: errMessage,
        grouping: true,
        type: "error"
      })

      return Promise.reject(errMessage)
    }
  )
  return service
}

/** 创建请求方法 */
function createRequest(service: AxiosInstance) {
  return function <T>(config: AxiosRequestConfig): Promise<T> {
    const accessToken = getAccessToken()
    const defaultConfig = {
      headers: {
        // 携带 Token
        Authorization: accessToken ? `Bearer ${accessToken}` : undefined
      },
      timeout: 600000, // 10分钟
      baseURL: import.meta.env.VITE_APP_GLOB_BASE_API,
      data: {}
    }
    // 将默认配置 defaultConfig 和传入的自定义配置 config 进行合并成为 mergeConfig
    const mergeConfig = merge(defaultConfig, config)
    return service(mergeConfig)
  }
}

/** 用于网络请求的实例 */
const service = createService()
/** 用于网络请求的方法 */
const request = createRequest(service)

export default request
